package com.ocm.tourism.file;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;


public class ScaleImageService{

   public static final int DEFAULT_SCALE_SMALL_WIDTH=64;

   public static final int DEFAULT_SCALE_MEDIUM_WIDTH=200;

   public static final int DEFAULT_SCALE_LIMIT_SIZE=50000;


   public MetadataScaleFile scaleMedium(InputStream file, String mimeType) throws Exception {
      BufferedImage bufferedImage = ImageIO.read(file);
      if (bufferedImage != null){
         BufferedImage smallThumbnail = scaleMedium(bufferedImage);
         MetadataScaleFile small = getMetadataScaleFile(smallThumbnail, mimeType);
         return small;
      }
      return null;
   }

   public MetadataScaleFile scaleSmall(InputStream file, String mimeType) throws Exception {
      BufferedImage bufferedImage = ImageIO.read(file);
      if (bufferedImage != null){
         BufferedImage smallThumbnail = scaleSmall(bufferedImage);
         MetadataScaleFile small = getMetadataScaleFile(smallThumbnail, mimeType);
         return small;
      }
      return null;
   }

   private BufferedImage scaleSmall(BufferedImage bufferedImage) throws IOException{
      BufferedImage thumbnail = Scalr.resize(bufferedImage, Method.ULTRA_QUALITY, Scalr.Mode.FIT_TO_WIDTH, getFitSmallWidth(bufferedImage.getWidth()));
      return thumbnail;
   }
   
   private BufferedImage scaleMedium(BufferedImage bufferedImage) throws IOException{
      BufferedImage thumbnail = Scalr.resize(bufferedImage, Method.ULTRA_QUALITY, Scalr.Mode.FIT_TO_WIDTH, getFitMediumWidth(bufferedImage.getWidth()));
      return thumbnail;
   }
   

   private int getFitSmallWidth(int width){
      int expected = (width < DEFAULT_SCALE_SMALL_WIDTH) ? width : DEFAULT_SCALE_SMALL_WIDTH;
      return expected;
   }

   private int getFitMediumWidth(int width){
      int expected = (width < DEFAULT_SCALE_MEDIUM_WIDTH) ? width : DEFAULT_SCALE_MEDIUM_WIDTH;
      return expected;
   }
   
   private MetadataScaleFile getMetadataScaleFile(BufferedImage bufferedImage, String mimeType) throws Exception{
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ImageIO.write(bufferedImage, MimeTypeSupport.convertFormatName(mimeType), baos);
      baos.flush();
      byte[] bs = baos.toByteArray();
      baos.close();
      MetadataScaleFile metadataScaleFile = new MetadataScaleFile();
      metadataScaleFile.setHeight(bufferedImage.getHeight());
      metadataScaleFile.setWidth(bufferedImage.getWidth());
      metadataScaleFile.setSize(Long.parseLong(""+bs.length));
      metadataScaleFile.setBytes(bs);
      return metadataScaleFile;
   }
}
